<template>
    <div class="ml-16px mr-16px content-container">
        <div class="pl-26px pt-10px pb-10px">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="110px" class="pt-26px">
                <el-form-item label="项目名称" prop="name">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.name" v-model="ruleForm.name" placeholder="请输入完整公司名称"></el-input></div>
                </el-form-item>
                <el-form-item label="域名" prop="domains">
                    <div class="flex flex-col mb--10px">
                        <div class="flex items-center mb-10px w-630px" v-for="(item, index) in ruleForm.domains">
                            <div class="w-400px"><el-input :disabled="ruleForm.disabled.domains" v-model="ruleForm.domains[index].url"
                                    placeholder="www.abc.com，请将'http://'、'https://'等符号去除" class="w-400px"></el-input>
                            </div>
                            <div class="flex items-center w-120px ml-10px">
                                <el-select :disabled="ruleForm.disabled.domains" v-model="ruleForm.domains[index].titleid">
                                    <el-option label="公司站" value="1"></el-option>
                                    <el-option label="非公司站" value="2"></el-option>
                                </el-select>
                            </div>
                            <el-button v-if="!ruleForm.disabled.domains" class="ml-10px" @click="handleAddDomain()">+</el-button>
                            <el-button v-if="item.isNew" class="ml-10px" @click="handleRemoveDomain(index)">-</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="商铺地址" prop="shopUrl">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.shopUrl" v-model="ruleForm.shopUrl" placeholder="请输入商铺地址"></el-input></div>
                </el-form-item>
                <el-form-item label="FTP地址" prop="ftpIp">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.ftpIp" v-model="ruleForm.ftpIp" placeholder="FTP地址"></el-input></div>
                </el-form-item>
                <el-form-item label="FTP账号" prop="ftpAccount">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.ftpAccount" v-model="ruleForm.ftpAccount" placeholder="请输入FTP账号"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="FTP密码" prop="ftpPassword">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.ftpPassword" v-model="ruleForm.ftpPassword" placeholder="请输入FTP密码"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="端口号" prop="port">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.port" v-model="ruleForm.port" placeholder="请输入端口号"></el-input></div>
                </el-form-item>
                <el-form-item label="优化要求" prop="seo">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.port" v-model="ruleForm.port" placeholder="请输入优化要求"></el-input></div>
                </el-form-item>
                <el-form-item label="后台地址" prop="backendIp">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.backendIp" v-model="ruleForm.backendIp" placeholder="请输入后台地址"></el-input></div>
                </el-form-item>
                <el-form-item label="后台账号" prop="backendAccount">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.backendAccount" v-model="ruleForm.backendAccount" placeholder="请输入后台账号"></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="后台密码" prop="backendPassword">
                    <div class="flex flex-col w-400px"><el-input :disabled="ruleForm.disabled.backendPassword" v-model="ruleForm.backendPassword" placeholder="请输入后台密码"></el-input>
                    </div>
                </el-form-item>
            </el-form>
            <div class="w-full">
                <div class="flex ml-16px mr-16px pl-94px pb-26px" v-if="!checkSubmit()">
                    <el-button type="primary" @click="handleConfirm(ruleFormRef)">确定</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </div>
                <div class="flex items-center mr-26px mb-26px warning-tips" v-else>
                    <svg-icon size="18px" icon-class="error-warning-fill"></svg-icon>注解：您已经提交过项目,如需调整,请联系客服人员
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { getProjectApi, addProjectApi } from '@/api/sem/index'
import type { FormInstance } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import { confirmMessageBox } from '@/utils/elMessageBox'

const ruleFormRef = ref()

const ruleForm = reactive({
    id: 0,
    pid: 0,
    name: '',
    domains: <{url:string,titleid:string,isNew?:boolean}[]>[],
    shopUrl: '',
    ftpIp: '',
    ftpAccount: '',
    ftpPassword: '',
    port: '',
    seo: '',
    backendIp: '',
    backendAccount: '',
    backendPassword: '',
    disabled: {
        name: false,
        domains: false,
        shopUrl: false,
        ftpIp: false,
        ftpAccount: false,
        ftpPassword: false,
        port: false,
        seo: false,
        backendIp: false,
        backendAccount: false,
        backendPassword: false,
    }
})

const rules = reactive({
    name: [
        { required: true, message: '请输入完整公司名称', trigger: 'blur' }
    ],
    domains: [
        { required: true,trigger: 'blur', validator: checkDomains }
    ],
    shopUrl: [
        { required: true, message: '请输入商铺地址', trigger: 'blur' }
    ]
})


function handleReset() {
    ruleForm.id = 0
    ruleForm.pid = 0
    ruleForm.name = ''
    ruleForm.shopUrl = ''
    ruleForm.domains = [
        {
            url:'',
            titleid:'1',
            isNew:false
        }
    ]
    ruleForm.ftpIp = ''
    ruleForm.ftpAccount = ''
    ruleForm.ftpPassword = ''
    ruleForm.port = ''
    ruleForm.seo = ''
    ruleForm.backendIp = ''
    ruleForm.backendAccount = ''
    ruleForm.backendPassword = ''
}

function handleAddDomain(){
    const hasEmptyString = ruleForm.domains.some((obj) => obj.url === '')
    if (hasEmptyString) {
        ElMessage.error('请按要求输入域名后，才可以继续添加！')
        return
    }else{
        ruleForm.domains.push({
            url:'',
            titleid:'1',
            isNew:true
        })
    }
}

function handleRemoveDomain(index:number){
    ruleForm.domains.splice(index,1)
}

function checkDomains(rule: any, value: any, callback: any) {
    if (value.length === 0 || value[0].url === '') {
        callback(new Error('请按要求输入域名'))
    } else {
        // 验证完整域名格式，如 www.abc.com
        const domainPattern = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
        
        for (let i = 0; i < value.length; i++) {
            let url = value[i].url;
            if (url) {
                // 如果包含协议，则移除协议部分
                if (url.includes('://')) {
                    url = url.split('://')[1];
                }
                
                // 移除端口号（:8080等）
                url = url.replace(/:\d+$/, '');
                
                // 移除路径部分（/path等）
                url = url.replace(/\/.*$/, '');
                
                // 验证完整域名格式
                if (!domainPattern.test(url)) {
                    callback(new Error(`域名 "${value[i].url}" 格式不正确，请输入类似 "www.abc.com" 的完整域名格式`))
                    return
                }
            }
        }
        callback()
    }
}

async function handleConfirm(formEl: FormInstance | undefined) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            const res: ResType = await addProjectApi({
                ID: ruleForm.id,
                Pid: ruleForm.pid,
                ProjectName: ruleForm.name,
                UrlJson: ruleForm.domains,
                ShopUrl: ruleForm.shopUrl,
                FtpContent: [
                    {
                        ftppassword: ruleForm.ftpAccount,
                        ftpurl: ruleForm.ftpIp,
                        ftpusername: ruleForm.ftpPassword,
                        port: ruleForm.port,
                        requirement: ruleForm.seo,
                        urladmin: ruleForm.backendIp,
                        urlpassword: ruleForm.backendPassword,
                        urlusername: ruleForm.backendAccount
                    }
                ],
            })
            if (res.code === 200) {
                confirmMessageBox(SuccessFilled, res.message)
                getProject()
            }
        } else {
            
        }
    })
}

async function getProject() {
    const res: ResType = await getProjectApi()
    console.log(res)
    if (res.code === 200) {
        ruleForm.id = res.data.ID
        ruleForm.pid = res.data.Pid
        ruleForm.name = res.data.ProjectName
        ruleForm.shopUrl = res.data.ShopUrl
        ruleForm.domains = res.data.UrlJson
        ruleForm.ftpIp = res.data.FtpContent[0].ftpurl
        ruleForm.ftpAccount = res.data.FtpContent[0].ftpusername
        ruleForm.ftpPassword = res.data.FtpContent[0].ftppassword
        ruleForm.port = res.data.FtpContent[0].port
        ruleForm.seo = res.data.FtpContent[0].requirement
        ruleForm.backendIp = res.data.FtpContent[0].urladmin
        ruleForm.backendAccount = res.data.FtpContent[0].urlusername
        ruleForm.backendPassword = res.data.FtpContent[0].urlpassword

        if(res.data.ProjectName){
            ruleForm.disabled.name = true
        }
        if(res.data.UrlJson[0].url){
            ruleForm.disabled.domains = true
        }
        if(res.data.ShopUrl){
            ruleForm.disabled.shopUrl = true
        }
        // 优化：先检查 FtpContent 是否存在且不为空数组，避免访问不存在的属性
        if(res.data.FtpContent && res.data.FtpContent.length > 0){
            const ftpContent = res.data.FtpContent[0];
            if(ftpContent.ftpusername){
                ruleForm.disabled.ftpAccount = true
            }
            if(ftpContent.ftppassword){
                ruleForm.disabled.ftpPassword = true
            }
            if(ftpContent.ftpurl){
                ruleForm.disabled.ftpIp = true
            }
            if(ftpContent.port){
                ruleForm.disabled.port = true
            }
            if(ftpContent.requirement){
                ruleForm.disabled.seo = true
            }
            if(ftpContent.urladmin){
                ruleForm.disabled.backendIp = true
            }
            if(ftpContent.urlusername){
                ruleForm.disabled.backendAccount = true
            }
            if(ftpContent.urlpassword){
                ruleForm.disabled.backendPassword = true
            }
        }
    }
}

function checkSubmit() {
    return ruleForm.disabled.name && ruleForm.disabled.domains && ruleForm.disabled.shopUrl
}

onMounted(() => {
    getProject()
})
</script>

<style scoped></style>